const path = require('path');
const glob = require('glob');
const fs = require('fs-extra');
const chalk = require('chalk');
const { spawn } = require('child_process');
const handlebars = require('handlebars');
/**
 * abc-xyz => AbcXyz
 * @param {*} str 
 */
const varCase = str => str.replace(/-[a-z]/g, m => m[1].toUpperCase()).replace(/^.{1}/, m => m.toUpperCase());
const lowCase = str => str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`).replace(/^-/, '');
(async()=>{
    //获取指令输入的第二个字符串
    const command = process.argv[2] 
    console.log(chalk.green(`生成command:${command}`));
    const dirName = lowCase(command);
    const componentName = varCase(command);
    console.log(chalk.green(`文件名是:${dirName}`));
    console.log(chalk.green(`组件名是:${componentName}`));
    spawn('mkdir', ['-p', path.join(process.cwd(), `src/${dirName}`)]);
    //同步获取文件模板,这个方法吗，会返回一个文件流数组对象
    tplFiles = glob.sync(path.join(__dirname,'template/*.hbs'))
    tplFiles.forEach((async fileItem=>{
        //将文件以UTF-8的形式获取
        const content = await fs.readFile(fileItem,'utf-8')
        //编译模板文件-获取内容
        const tempalte = handlebars.compile(content);

        const result = tempalte({
            dirName,
            componentName
        })
        //替换文件，和扩展名。
        const newPath = fileItem.replace('scripts/template', `src/${dirName}`)
        .replace('component', dirName)
        .replace('Component', componentName)
        .replace('.hbs', '');
        
        await fs.writeFile(newPath, result);

        console.log(chalk.green(`生成文件： ${newPath} 成功！`));

    }))
})()